package com.ease.framework.gef4p.figures.impl.edge {
   import com.ease.framework.gef4p.constant.DiagramConstant;
   import com.ease.framework.gef4p.figures.edge.IEdgeAnchor;
   import com.ease.framework.gef4p.figures.edge.IEdgeAnchorListener;
   import com.ease.framework.gef4p.figures.edge.IEdgeFigure;

   import flash.geom.Point;

   import mx.core.UIComponent;

   public class STNodeEdgeAnchorManager extends AbstractEdgeListener {
      public var sourceAnchor:IEdgeAnchor;
      public var targetAnchor:IEdgeAnchor;

      public function STNodeEdgeAnchorManager() {
         super();
         sourceAnchor = new EdgeAnchor();
         sourceAnchor.setLocationType(DiagramConstant.EDGE_ANCHOR_LOCATION_SOURCE);

         sourceAnchor.visible = false;
         targetAnchor = new EdgeAnchor();
         targetAnchor.setLocationType(DiagramConstant.EDGE_ANCHOR_LOCATION_TARGET);
         targetAnchor.visible = false;
      }

      override public function beforeCreateChildren(edgeFigure:IEdgeFigure):void {
         sourceAnchor.setEdge(edgeFigure);
         targetAnchor.setEdge(edgeFigure);
         if (edgeFigure is IEdgeAnchorListener) {
            sourceAnchor.registerListener(edgeFigure as IEdgeAnchorListener);
            targetAnchor.registerListener(edgeFigure as IEdgeAnchorListener);
         }
      }

      override public function beforeDrawing(edgeFigure:IEdgeFigure):void {

         if (edgeFigure is EdgeFigure) {
            var source:Bend = (edgeFigure as EdgeFigure).getSourceBend();
            if (source != null) {
               sourceAnchor.setLocationStagePoint(edgeFigure.localToGlobal(new Point(source.x, source.y)));
               UIComponent(sourceAnchor).invalidateDisplayList();
            }

            var target:Bend = (edgeFigure as EdgeFigure).getTargetBend();
            if (target != null) {
               targetAnchor.setLocationStagePoint(edgeFigure.localToGlobal(new Point(target.x, target.y)));
               UIComponent(targetAnchor).invalidateDisplayList();
            }
         }
      }

      override public function select(edgeFigure:IEdgeFigure):void {
         sourceAnchor.visible = edgeFigure.isSelected;
         targetAnchor.visible = edgeFigure.isSelected;
      }
   }
}